package gw.com.android.ui.onlive;

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gwtsz.gts2.hx.R;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.ui.PraiseAndTransmitAdapter;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.ui.onlive.component.ActiveButton;
import gw.com.android.ui.views.ExpandableTextView;
import gw.com.android.ui.views.GlideCircleTransform;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.CommentsHelper;
import gw.com.android.utils.CopyShowerUtil;
import gw.com.android.utils.ImageLayoutHelper;
import gw.com.android.utils.PackStatis;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.util.DeviceUtil;
import www.com.library.util.StringFormatter;

/**
 * @author reeta.zou on 2016/7/13.
 */
public class DiscussAdapter extends PraiseAndTransmitAdapter {
    /**
     * 左边菜单栏适配器数据对象
     */
    private LayoutInflater mInflater;
    private ImageWatcher watcher;

    private List<DiscussData> mDatas;

    private MyConcernRequest myConcernRequest;
    private boolean ifHideConcernButton = false;
    private boolean ifSetFollowed = false;

    private int mTradeType;//区分当前 处于哪个list下

    DiscussAdapter(int tradeType, Activity mActivity) {
        super(mActivity);
        this.mTradeType = tradeType;
        mInflater = mActivity.getLayoutInflater();
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
    }

    public void setWatcher(ImageWatcher watcher) {
        this.watcher = watcher;
    }

    /**
     * 上拉刷新替换新数据
     */
    public void setData(List<DiscussData> list, String[] followedAnalyst, boolean ifHideConcernButton, boolean ifSetFollowed) {
        mDatas = list;
        this.ifSetFollowed = ifSetFollowed;
        this.followedAnalyst = followedAnalyst;
        this.ifHideConcernButton = ifHideConcernButton;
        notifyDataSetChanged();
    }

    public List<String> getIds() {
        List<String> ids = new ArrayList<>();
        if (mDatas == null) return ids;
        for (int i = 0; i < mDatas.size(); i++) {
            ids.add(mDatas.get(i).id);
        }
        return ids;
    }

    private String[] followedAnalyst;

    private void setFollowedAnalyst(String[] followedAnalyst) {
        this.followedAnalyst = followedAnalyst;
    }

    /**
     * 检查是否已经关注了该分析师
     */
    private boolean checkIfFollowed(String analystUserNo) {
        boolean res = false;
        for (int i = 0; i < followedAnalyst.length; i++) {
            if (followedAnalyst[i] == null) break;
            if (followedAnalyst[i].equals(analystUserNo)) {
                res = true;
                break;
            }
        }
        return res;
    }

    /**
     * 上拉刷新追加数据
     */
    public void addData(List<DiscussData> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        if (mDatas == null) {
            mDatas = list;
        } else {
            mDatas.addAll(list);
        }
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.list_item_home_discuss, parent, false);
        return new ItemHolder(itemView);
    }

    /**
     * 根据position返回界面item数据对象
     */
    public DiscussData getItem(int position) {
        if (mDatas != null) {
            if (position >= 0 && position < mDatas.size()) {
                return mDatas.get(position);
            }
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final ItemHolder mHolder = (ItemHolder) holder;
        DiscussData mItem = getItem(position);//item 复用
        if (null != mItem) {
            mHolder.itemView.setTag(position);
            mHolder.mContentview.setConvertText(true, mItem.remark);
            new CopyShowerUtil(mContext, mHolder.expandable_text);
            mHolder.mNameview.setText(TextUtils.isEmpty(mItem.userName) ? mItem.createUser : mItem.userName);
            mHolder.mNameview.setTag(mItem.accountNo);
            mHolder.mContentview.setTag(mItem.userNo);

            //区分是不是精华帖
            int best = mItem.best;
            if (best == 1) {
                mHolder.tv_best.setVisibility(View.VISIBLE);
            } else {
                mHolder.tv_best.setVisibility(View.GONE);
            }

            mHolder.discuss_transmit_container.setOnClickListener(null);
            //获得分享数
            dealCount(mHolder.tv_transmit_count, mItem.transmit);//这里，直接加载mData中的分享数
            initTransmitLayout(mItem.id, mItem.transmit, mHolder.tv_transmit_count);//这里，加载缓存中的分享数

            ShareClickListener lis = new ShareClickListener(mItem.id, mItem.remark, mHolder.tv_transmit_count, mItem.transmit, EVENT_FROM_DISCUSS);
            mHolder.discuss_transmit_container.setOnClickListener(lis);//給这两个组件的父容器设置点击事件

            //区分是不是置顶帖
            int sorted = mItem.sorted;
            if (sorted == 1) {
                mHolder.tv_sort_1.setVisibility(View.VISIBLE);
            } else {
                mHolder.tv_sort_1.setVisibility(View.GONE);
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
            df.setTimeZone(TimeZone.getTimeZone("GMT+0"));

            try {
                Date date = df.parse(mItem.showDate);
                mHolder.mTimeview.setText(StringFormatter.instance().toDateTimeHM(date));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            mHolder.discuss_like_container.setOnClickListener(new PraiseLis(mItem, mHolder.mLikeEffect, mHolder.mPraiseBtn, mHolder.mLikeIcon));

            dealCount(mHolder.mPraiseBtn, mItem.praise);//这里，直接加载mData中的点赞数
            initPraiseLayout(mItem.id, mHolder.mLikeIcon, mHolder.mPraiseBtn);////这里，加载缓存中的点赞数

            Glide.with(mContext).load(mItem.avatar)
                    .placeholder(R.mipmap.a_show_profiles)
                    .error(R.mipmap.a_show_profiles)
                    .bitmapTransform(new GlideCircleTransform(mContext))
                    .into(mHolder.mUserImageView);//加载用户头像

            // 用标志区分分析师或者客户晒单
            int tradeType = mItem.tradeType;//
            mHolder.mNameview.setOnClickListener(null);//recyclerView的复用机制，很容易搞出 残留UI，残留eventListener的问题，所以，要记住用recyclerView，有增就有减，有set就有remove，有if就一定有else。不然后果自负。。
            mHolder.mUserImageView.setOnClickListener(null);
            mHolder.ll_vip.setOnClickListener(null);
            mHolder.ll_concern_btn.setOnClickListener(null);//有setListener(lis)就要有setListener(null).深深领教了复用机制带来的麻烦
            if (tradeType == 1) {//1，分析师晒单
                mHolder.iv_analyst_tag.setVisibility(View.VISIBLE);
                mHolder.val_main.setVisibility(View.GONE);
                mHolder.iv_vip_guest_tag2.setVisibility(View.GONE);

                AnalystOnClickListener onClickListenerEX = new AnalystOnClickListener((String) mHolder.mContentview.getTag(), (String) mHolder.mNameview.getTag(), (Activity) mContext);
                boolean ifFollowed = checkIfFollowed(mItem.userNo);
                if (ifFollowed) {
                    if (ifHideConcernButton) {//这个值用来控制是不是让关注按钮消失
                        Log.d("checkIfFollowed", "已关注该分析师:" + mItem.accountNo);
                        mHolder.ll_concern_btn.setVisibility(View.GONE);//关注的按钮消失
                    } else {
                        mHolder.ll_concern_btn.switchToFollowed();
                        if (ifSetFollowed)
                            mHolder.ll_concern_btn.setVisibility(View.VISIBLE);
                        else
                            mHolder.ll_concern_btn.setVisibility(View.GONE);
                    }
                } else {//如果没关注它，那就
                    Log.d("checkIfFollowed", "没有关注该分析师:" + mItem.accountNo);
                    mHolder.ll_concern_btn.setVisibility(View.VISIBLE);//关注的按钮显示
                    mHolder.ll_concern_btn.switchToAddFollow();
                }

                mHolder.ll_concern_btn.setOnClickListener(new FollowOnClickListener(mHolder.ll_concern_btn, GTConfig.instance().mCurName, mItem.userNo));//并且给按钮设置事件，点击之后可以调用接口进行关注
                mHolder.mNameview.setOnClickListener(onClickListenerEX);
                mHolder.mUserImageView.setOnClickListener(onClickListenerEX);
            } else {//，2 客户晒单; 如果是客户晒单，那么要区分当前用户是不是VIP
                mHolder.iv_analyst_tag.setVisibility(View.GONE);
                mHolder.ll_concern_btn.setVisibility(View.GONE);

                if (mItem.ifVip())//当前用户是VIP
                {
                    mHolder.val_main.setVipId(mTradeType,mItem.id);
                    mHolder.val_main.setVisibility(View.VISIBLE);
                    mHolder.iv_vip_guest_tag2.setVisibility(View.GONE);
                } else {
                    mHolder.val_main.setVisibility(View.GONE);
                    mHolder.iv_vip_guest_tag2.setVisibility(View.VISIBLE);
                }
                mHolder.ll_vip.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //点击这个灰色的VIP图，之后，弹出一个框，
                        PackStatis.getToService("clickVIP", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
                        showVipDialog();
                    }
                });
            }
            //加载用户上传的图片
            String s = mItem.tradeImgs;
            if (TextUtils.isEmpty(s)) {//为了兼容旧数据，必须这么做（因为旧的数据并没有tradeImgs这个字段，所以必须手动造）
                String tradeImg = mItem.tradeImg;
                s = "[\"" + tradeImg + "\"]";
            }
            Log.d("tradeImg", "" + s);
            //如果返回值不包含中括号，应该就是一张图的情况，这个时候，就按照一张图处理
            final List<ImageView> images = new ArrayList<>();
            final List<String> urlList = new ArrayList<>();
            mHolder.ll_trade_image.removeAllViews();
            mHolder.ll_trade_image_for_only_one.removeAllViews();
            if (!TextUtils.isEmpty(s)) {
                Type type = new TypeToken<ArrayList<String>>() {
                }.getType();
                List<String> shaidanImageList = new Gson().fromJson(s, type);//GSON解析数组的方式也是很诡异，和Fastjson完全不同
                if (mItem.type == 0 /* 晒单 */) {
                    mHolder.ll_trade_image.setVisibility(View.GONE);
                    mHolder.ll_trade_image_for_only_one.setVisibility(View.VISIBLE);
                    ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, mHolder.ll_trade_image_for_only_one, shaidanImageList.get(0), images, urlList);
                } else if (shaidanImageList.size() == 1) {//如果不包含中括号，就是只有一张图
                    mHolder.ll_trade_image.setVisibility(View.GONE);
                    mHolder.ll_trade_image_for_only_one.setVisibility(View.VISIBLE);
                    ImageLayoutHelper.getInstance(watcher).setSizeofSingleImg(mContext, mItem.imgSize);
                    ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, 0, mHolder.ll_trade_image_for_only_one, shaidanImageList.get(0), images, urlList, true);

                } else {//否则就是多张图的情况，要进行JSON解析 ，json大概是这样的["1.png","2.png"]
                    mHolder.ll_trade_image.setVisibility(View.VISIBLE);
                    mHolder.ll_trade_image_for_only_one.setVisibility(View.GONE);

                    for (int i = 0; i < shaidanImageList.size(); i++) {//轮流创建imageView并且加载到布局中
                        ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, i, mHolder.ll_trade_image, shaidanImageList.get(i), images, urlList, false);
                    }
                }
            }

            List<Comment> comments = mItem.comments;
            CommentsHelper.getInstance().addComment(mContext, mHolder.ll_comments, mInflater, comments, mHolder.iv_triangle);

            ViewGroup.LayoutParams params = mHolder.v_sep.getLayoutParams();
            //处理分割线
            if (position + 1 == getItemCount()) {// 如果是最后一项，就隐藏分割线
                params.height = 0;
            } else {
                params.height = DeviceUtil.instance().dip2px(10, mContext);
            }
            mHolder.v_sep.setLayoutParams(params);
        }
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }


    /**
     * item视图控件对象
     *
     * @author Administrator
     */
    class ItemHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.user_icon)
        ImageView mUserImageView;
        @BindView(R.id.ll_trade_image)
        LinearLayout ll_trade_image;
        @BindView(R.id.ll_trade_image_for_only_one)
        LinearLayout ll_trade_image_for_only_one;
        @BindView(R.id.tv_news_time)
        TextView mTimeview;
        @BindView(R.id.tv_news_content)
        ExpandableTextView mContentview;
        @BindView(R.id.expandable_text)
        TextView expandable_text;
        @BindView(R.id.tv_name_title)
        TextView mNameview;
        @BindView(R.id.praise_button)
        TextView mPraiseBtn;
        @BindView(R.id.discuss_like)
        ImageView mLikeIcon;
        @BindView(R.id.discuss_like_effect)
        ImageView mLikeEffect;
        @BindView(R.id.iv_analyst_tag)
        ImageView iv_analyst_tag;
        @BindView(R.id.ll_concern_btn)
        ActiveButton ll_concern_btn;
        @BindView(R.id.iv_vip_guest_tag)
        ImageView iv_vip_guest_tag;
        @BindView(R.id.iv_vip_guest_tag2)
        ImageView iv_vip_guest_tag2;
        @BindView(R.id.tv_best)
        TextView tv_best;
        @BindView(R.id.tv_sort_1)
        TextView tv_sort_1;
        @BindView(R.id.tv_transmit_count)
        TextView tv_transmit_count;
        @BindView(R.id.iv_transmit)
        ImageView iv_transmit;
        @BindView(R.id.ll_comments)
        LinearLayout ll_comments;
        @BindView(R.id.discuss_transmit_container)
        LinearLayout discuss_transmit_container;
        @BindView(R.id.v_sep)
        View v_sep;
        @BindView(R.id.iv_triangle)
        ImageView iv_triangle;
        @BindView(R.id.discuss_like_container)
        LinearLayout discuss_like_container;
        @BindView(R.id.ll_vip)
        LinearLayout ll_vip;
        @BindView(R.id.val_main)
        VipAnimatorLayout val_main;

        ItemHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            mContentview.setExpandCollapseHintText(AppMain.getAppString(R.string.expandable_expand), AppMain.getAppString(R.string.expandable_collapse));
            //给点赞区域增加点击事件
        }

    }

    /**
     * 分析师名字头像的点击事件
     */
    class AnalystOnClickListener implements View.OnClickListener {

        String accountNo;
        String userNo;
        Activity context;

        AnalystOnClickListener(String userNo, String accountNo, Activity context) {
            this.accountNo = accountNo;
            this.userNo = userNo;
            this.context = context;
        }

        @Override
        public void onClick(View v) {
            PackStatis.getToService("clickTeacher1", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
            ActivityManager.showAnalystPage(userNo, accountNo, context);
        }
    }

    /**
     * +关注、取消关注 按钮的点击事件
     */
    class FollowOnClickListener implements View.OnClickListener {

        private ActiveButton activeButton;
        private String userId;//当前登录用户的no
        private String analystNo;//要关注或者取消关注的分析师NO

        FollowOnClickListener(ActiveButton activeButton, String userId, String analystNo) {
            this.activeButton = activeButton;
            this.userId = userId;
            this.analystNo = analystNo;
        }

        @Override
        public void onClick(View v) {

            //检测登录状态，如果当前是游客状态，那就説明沒有登录
            boolean ifGuest = GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST;
            if (ifGuest) {
                new ToastPopWindow(mContext, "登录之后才能关注").show();
                return;
            }

            //判定当前是不是真实用户
            if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {//如果不是真实用户
                PackStatis.getToService("clickConcern1", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
                new ToastPopWindow(mContext, "真实用户才能关注哦").show();
                return;
            }
            //如果是+关注的状态，那么就调用+关注接口（同时切换成progressing状态），然后根据接口返回值决定是不是要变换到 已关注。
            activeButton.switchToProgressBar();
            if (activeButton.getCurrentStatu() == ActiveButton.STATU_ADD_FOLLOW) {// 如果按钮显示的是 +关注
                setFollow(userId, analystNo, MyConcernRequest.CONST_ADD_FOLLOW, new HttpCallback<String>() {
                    @Override
                    public void onSuccess(String result) {//如果添加关注成功
                        //请求正常返回了,
                        //来判断返回值是true还是false
                        if ("true".equals(result)) {
                            new ToastPopWindow(mContext, "关注成功").show();
                            activeButton.switchToFollowed();
                        } else {
                            new ToastPopWindow(mContext, "关注失败，请重新关注~").show();
                            activeButton.switchToAddFollow();
                        }
                        refreshFollowedAnalyst();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        new ToastPopWindow(mContext, "请求超时，请重新关注~").show();
                        activeButton.switchToAddFollow();
                    }
                });
            } else {// 如果当前显示的是已关注，那么点击之后，就可以取消关注，调用取消关注接口
                setFollow(userId, analystNo, MyConcernRequest.CONST_CANCEL_FOLLOW, new HttpCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if ("true".equals(result)) {
                            new ToastPopWindow(mContext, "取消成功").show();
                            activeButton.switchToAddFollow();
                        } else {
                            new ToastPopWindow(mContext, "关注失败，请重新关注~").show();
                            activeButton.switchToFollowed();
                        }
                        refreshFollowedAnalyst();

                    }

                    @Override
                    public void onFailure(Exception e) {
                        new ToastPopWindow(mContext, "请求超时，请重新取消关注~").show();
                        activeButton.switchToFollowed();
                    }
                });
            }
        }
    }

    private void setFollow(final String userNo, final String analystNo, int ifFollow, HttpCallback<String> callback) {
        myConcernRequest.addOrRemoveFollowedAnalystList(userNo, analystNo, ifFollow, callback);
    }

    private void showVipDialog() {
        View root = LayoutInflater.from(mContext).inflate(R.layout.dialog_to_be_vip, null, false);
        View iv_close = root.findViewById(R.id.iv_close);
        TextView tv_open_permission = (TextView) root.findViewById(R.id.tv_open_permission);
        final VipDialog alertDialog = new VipDialog(mContext, 0, 0, root, R.style.VipDialog);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        tv_open_permission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PackStatis.getToService("clickLight", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
                ConfigSettingDeal mDeal = new ConfigSettingDeal();
                mDeal.openQQ((Activity) mContext, ConfigType.QQ_SOURCE_VIP);
                PackStatis.getToService(PackStatis.EventAction.CLICKSERVICE.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, null);
                alertDialog.dismiss();
            }
        });

        alertDialog.show();
    }

    //=============================下面是分享弹窗相关的=================================================


    //=========获取已关注的分析师===========
    private void refreshFollowedAnalyst() {//在成功关注了某个分析师之后调用
        ifSetFollowed = true;
        // 进入这个页面之前，先取出我关注的分析师
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
        //如果是登录了，那就先获取当前用户关注的分析师；因为这里涉及到RecyclerView的item复用，必须先把关注情况记录下来，防止在滑动的时候造成 关注状态混乱
        myConcernRequest.getFollowedAnalystList(GTConfig.instance().mCurName, new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                if (result == null)
                    followedAnalyst = new String[]{};
                else {
                    followedAnalyst = new String[result.size()];
                    int i = 0;
                    for (AnalystData data : result) {
                        followedAnalyst[i] = data.userNo;
                        i++;
                    }
                }

                setData(mDatas, followedAnalyst, false, ifSetFollowed);
            }

            @Override
            public void onFailure(Exception e) {
                Log.d("QuanziListTag1", "侦测到请求异常，可能是网络原因，可能是后台原因: " + e == null ? "exception是空" : e.getLocalizedMessage());
            }
        });
    }

}
